package org.pim.smart.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.plugin.AbstractUIPlugin;

public class CacheImage {
	
	private final Map<String, Image> imageMap = new HashMap<String, Image>();
	private static CacheImage INSTANCE = new CacheImage();
	
	private CacheImage() {}
	
	public static CacheImage getINSTANCE(){
		return INSTANCE;
	}
	
	public Image getImage(String applicationID, String imageName){
		if (imageName == null){
			return Display.getCurrent().getSystemImage(SWT.ICON_ERROR);
		}
		Image image = (Image)imageMap.get(imageName);
		if (image == null){
			try{
				image = AbstractUIPlugin.imageDescriptorFromPlugin(applicationID, imageName).createImage();
			}catch(Exception e){
				image = Display.getCurrent().getSystemImage(SWT.ICON_ERROR);
			}
			imageMap.put(imageName, image);
		}
		return image;
	}
	
	public void dispose(){
		Iterator<Image> iterator = imageMap.values().iterator();
		while (iterator.hasNext()){
			((Image)iterator.next()).dispose();
		}
		imageMap.clear();
	}
	
	public Image getLocalImage(String imageName){
		return this.getImage(IAppConstant.application_id, imageName);
	}
}
